package com.hch.maker.template;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.hch.maker.template.enums.FileFilterRangeEnum;
import com.hch.maker.template.enums.FileFilterRuleEnum;
import com.hch.maker.template.model.FileFilterConfig;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 86134
 * @version 1.0
 * @description TODO
 * @date 2024/7/31 14:31
 */

public class FileFilter {

    public static List<File> doFilter(String filePath, List<FileFilterConfig> fileFilterConfigList){
        List<File> files = FileUtil.loopFiles(filePath);
        return files.stream().filter(file -> doSingleFileFilter(fileFilterConfigList,file)).collect(Collectors.toList());
    }

    public static boolean doSingleFileFilter(List<FileFilterConfig> fileFilterConfigList, File file){
        String fileName = file.getName();
        String fileContent = FileUtil.readUtf8String(file);

        //过滤器的结果
        boolean result = true;

        if(CollUtil.isEmpty(fileFilterConfigList)){
            return true;
        }

        for (FileFilterConfig fileFilterConfig : fileFilterConfigList) {
            String range = fileFilterConfig.getRange();
            String rule = fileFilterConfig.getRule();
            String value = fileFilterConfig.getValue();

            FileFilterRangeEnum filterRangeEnum = FileFilterRangeEnum.getEnumByValue(range);
            if(filterRangeEnum == null){
                continue;
            }

            String context = fileName;
            switch (filterRangeEnum){
                case FILE_NAME:context = fileName;break;
                case FILE_CONTENT: context = fileContent;break;
            }

            FileFilterRuleEnum filterRuleEnum = FileFilterRuleEnum.getEnumByValue(rule);
            if(filterRuleEnum == null){
                continue;
            }
            switch (filterRuleEnum){
                case CONTAINS:result = context.contains(value);break;
                case STATIC_WITH:result = context.startsWith(value);break;
                case ENOS_WITH:result = context.endsWith(value);break;
                case REGEX:result = context.matches(value);break;
                case EQUALS:result = context.equals(value);break;
            }
            if(!result){
                return false;
            }


        }

        return true;
    }

}
